package com.sea.supply.service.impl;


import com.codecrane.core.util.CommonUtils;
import com.sea.data.entity.*;
import com.sea.data.mapper.OrderMapper;
import com.sea.finance.entity.ExchangeRate;
import com.sea.finance.service.ExchangeRateService;
import com.sea.product.entity.Product;
import com.sea.product.service.ProductService;
import com.sea.supply.entity.*;
import com.sea.supply.mapper.BuyMapper;
import com.sea.data.service.*;
import com.sea.supply.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 陈鸿飞
 */
@Service
public class BuyServiceImpl implements BuyService {

    @Autowired
    private BuyMapper buyMapper;
    @Autowired
    private ProduceService produceService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private ProduceDetailService produceDetailService;
    @Autowired
    private ProduceRecordService produceRecordService;
    @Autowired
    private ProduceNodeService produceNodeService;
    @Autowired
    private QualityProduceService qualityProduceService;
    @Autowired
    private QualityProduceDetailService qualityProduceDetailService;
    @Autowired
    private ExchangeRateService exchangeRateService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SupplierService supplierService;

    @Autowired
    private OrderMapper orderMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(Buy buy) {
        return buyMapper.insert(buy);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int split(Buy buy) {
        if(buy.getBuyNumber().equals(0)){
            throw new RuntimeException("拆分数量不能为0！");
        }
        //找到老数据
        Buy oldBuy = buyMapper.findById(buy.getId());
        if(buy.getBuyNumber().equals(oldBuy.getBuyNumber())){
            throw new RuntimeException("拆分数量不能和请购数量一致！");
        }
        if(buy.getBuyNumber()>(oldBuy.getBuyNumber())){
            throw new RuntimeException("拆分数量不能大于请购数量！");
        }
        //更新现有数据
        buy.setOrderId(oldBuy.getOrderId());
        buy.setDetailId(oldBuy.getDetailId());
        //老数据减掉拆分的量
        oldBuy.setBuyNumber(oldBuy.getBuyNumber()-buy.getBuyNumber());
        //更新原有数据
        buyMapper.update(oldBuy);
        return buyMapper.insert(buy);
    }

    @Override
    public List<Buy> findByCnd(Buy buy) {
        if(null!=buy.getProductColorIds() && buy.getProductColorIds().length==0){
            buy.setProductColorIds(null);
        }
        if(null!=buy.getProductSizeIds() && buy.getProductSizeIds().length==0){
            buy.setProductSizeIds(null);
        }
        if(null!=buy.getOrderIds() && buy.getOrderIds().length==0){
            buy.setOrderIds(null);
        }
        return buyMapper.findByCnd(buy);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String produce(Integer[] ids, String supplierName,String produceMoneyType,String paymentType) {

        String colorMsg="";
        List<OrderDetail> sameData = orderDetailService.findSameData(ids);
        for( OrderDetail detail:sameData){
            if(detail.getOrderNumber()>1){
                throw new RuntimeException("相同交期不能生成采购单！SKU：【"+detail.getOrderSku()+"】");
            }
        }

        ExchangeRate rate = exchangeRateService.findByRateName("CNY", produceMoneyType);
        if(null==rate){
            throw new RuntimeException("暂未查询到该币种汇率信息！");
        }

        String orderNo = CommonUtils.fill(produceService.getMaxId(), 5, 7);
        //新增产前质检数据
        QualityProduce qualityProduce=new QualityProduce();
        //节点新增
        ProduceNode produceNode=new ProduceNode();
        Produce produce=new Produce();
        produce.setProduceNo("PO"+orderNo);
        produce.setProduceSupplierName(supplierName);
        produce.setProduceMoneyType(produceMoneyType);
        produce.setPaymentType(paymentType);
        Supplier bySupplierName = supplierService.findBySupplierName(supplierName);
        if(null !=bySupplierName.getSupplierDay()){
            produce.setSupplierDay(bySupplierName.getSupplierDay());
        }else{
            produce.setSupplierDay(0);
        }
        produceService.save(produce);
        produceNode.setProduceId(produce.getId());
        produceNodeService.save(produceNode);

        //产前新增
        qualityProduce.setProduceId(produce.getId());
        qualityProduceService.save(qualityProduce);
        //新增明细内容
        qualityProduceDetailService.addDetail(produce.getId());
        for(Integer id:ids){
            Buy buy = buyMapper.findById(id);
            Integer detailId = buy.getDetailId();
            OrderDetail detail = orderDetailService.findById(detailId);
            ProductPrice productPrice = productPriceService.findBySupplierChannelSku(supplierName, detail.getOrderChannelName(), detail.getOrderSku(),produceMoneyType);
            Double buyDiscount = buy.getBuyDiscount();
            if(null==productPrice){
                throw new RuntimeException("请先维护SKU供应商报价信息:"+detail.getOrderSku());
            }else{
                ProduceDetail produceDetail=new ProduceDetail();
                produceDetail.setProduceId(produce.getId());
                produceDetail.setBuyId(buy.getId());
                produceDetail.setDetailId(detail.getId());
                //含税单价
                if(null != buyDiscount && buyDiscount>0){
                    produceDetail.setProducePrice(productPrice.getProductPrice()*buyDiscount);
                    produceDetail.setProduceUnitPrice(productPrice.getProductUnitPrice()*buyDiscount);
                    produceDetail.setProducePriceCny(productPrice.getProductPrice()*buyDiscount*rate.getRatePercent());
                    produceDetail.setProduceUnitPriceCny(productPrice.getProductUnitPrice()*buyDiscount*rate.getRatePercent());
                    produceDetail.setProduceTotal(buy.getBuyNumber());
                    produceDetail.setProduceSurplus(buy.getBuyNumber());
                }else {
                    produceDetail.setProducePrice(productPrice.getProductPrice());
                    produceDetail.setProduceUnitPrice(productPrice.getProductUnitPrice());
                    produceDetail.setProducePriceCny(productPrice.getProductPriceCny());
                    produceDetail.setProduceUnitPriceCny(productPrice.getProductUnitPriceCny());
                    produceDetail.setProduceTotal(buy.getBuyNumber());
                    produceDetail.setProduceSurplus(buy.getBuyNumber());
                }

                //判断是否是增色单
                Integer result = produceDetailService.findByFirstProduce(detail.getOrderSku(), supplierName);
                if(result==0){
                    Product product = productService.findBySku(detail.getOrderSku());
                    colorMsg+=product.getProductName()+"<br />";
                    produceDetail.setProduceAddColor(1);
                }else{
                    produceDetail.setProduceAddColor(0);
                }

                produceDetailService.save(produceDetail);

                //设置以及生产过采购订单
                buy.setFlag(1);
                buyMapper.update(buy);
            }

        }
        produceRecordService.save(produce.getId(),1,"");
        produceService.updateProduceTotal(produce.getId());
        //更新关联的请购单号
        orderMapper.updateProduceNo();
        //更新采购单表头中的渠道
        produceService.updateChannelName();
        if(StringUtils.isNotBlank(colorMsg)){
            colorMsg+="以上为增色单";
        }
        return colorMsg;
    }

    @Override
    public Buy findById(Integer id) {
        return buyMapper.findById(id);
    }

    @Override
    public int usave(Buy buy) {
        return buyMapper.update(buy);
    }

    @Override
    public Integer findBuyTotal() {
        return buyMapper.findBuyTotal();
    }

    @Override
    public void updateOderDate(Integer[] ids, String buyDate) {
        //更新交期
        for(Integer id:ids){
            Buy buy=new Buy();
            buy.setBuyOrderDate(buyDate);
            buy.setId(id);
            usave(buy);
        }
    }

    @Override
    public void updateOderDiscount(Integer[] ids, Double buyDiscount) {
        buyDiscount=buyDiscount/100;
        //更新折扣
        for(Integer id:ids){
            Buy buy=new Buy();
            buy.setBuyDiscount(buyDiscount);
            buy.setId(id);
            usave(buy);
        }
    }

    @Override
    public void delOrder(Integer[] ids) {
        for(Integer id:ids){
            Buy buy=new Buy();
            buy.setId(id);
            buy.setFlag(1);
            usave(buy);
        }
    }

    @Override
    public void updateSupplierName(Integer[] ids, String supplierName) {
        //更新交期
        for(Integer id:ids){
            Buy buy = findById(id);

            buy.setSupplierName(supplierName);
            buyMapper.update(buy);
        }
    }

    @Override
    public List<Buy> findSupplierNameIsNull() {
        return buyMapper.findSupplierNameIsNull();
    }

    @Override
    public void updateBuySupplierName() {
        List<Buy> list = findSupplierNameIsNull();
        for(Buy buy:list){

            Integer detailId = buy.getDetailId();

            OrderDetail orderDetail = orderDetailService.findById(detailId);
            if(StringUtils.isNotBlank(orderDetail.getSupplierName())){
                buy.setSupplierName(orderDetail.getSupplierName());
                usave(buy);
            }
        }
    }

    @Override
    public List<Buy> testProduce(Integer orderId) {
        return buyMapper.testProduce(orderId);
    }

    @Override
    public List<Buy> findByOrderNo() {
        return buyMapper.findByOrderNo();
    }
}
